//
//  ScanViewController.m
//  FlyGift
//
//  Created by lanou3g on 15/7/17.
//  Copyright (c) 2015年 lanou3g. All rights reserved.
//

#import "ScanViewController.h"
#import <AVFoundation/AVFoundation.h>

@interface ScanViewController ()<AVCaptureMetadataOutputObjectsDelegate>
//布局
@property(nonatomic,strong)UIView * viewPreview;
@property(nonatomic,strong)UILabel * statusLabel;
@property(nonatomic,assign)BOOL upOrDown;//判断是上还是下

@property(nonatomic,strong)UIImageView * scanView;//扫描视图
@property(nonatomic,strong)UIImageView * boxImageView;//取景框

-(void)startReading;
-(void)stopReading;

//捕捉会话
@property(nonatomic,strong)AVCaptureSession * captureSession;
//展示layer
@property(nonatomic,strong)AVCaptureVideoPreviewLayer * videoPreviewLayer;
//定时器
@property(nonatomic,strong)NSTimer * timer;
@end

@implementation ScanViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBar.translucent = NO;
    self.navigationItem.title = @"扫一扫";
    self.view.backgroundColor = [UIColor whiteColor];
    [self loadMainView];
    _captureSession = nil;
    _upOrDown = NO;
    [self startReading];

}
-(void)loadMainView
{
    self.viewPreview = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth,kP6Height(400))];
    [self.view addSubview:_viewPreview];
    self.statusLabel = [[UILabel alloc]initWithFrame:CGRectMake(kP6width(10), kP6Height(450),kScreenWidth, kP6Height(30))];
    self.statusLabel.text = @"将取景框对准二维码,即可自动扫描";
    [self.viewPreview addSubview:_statusLabel];
}

#pragma mark --- 开始扫描 <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
-(void)startReading
{
    NSError * error;
    //1.初始化捕捉设备(AVCaptureDevice),类型为AVMediaTypeVideo
    AVCaptureDevice * captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    //2.用captureDevice 创建输入流
    AVCaptureDeviceInput * input = [AVCaptureDeviceInput deviceInputWithDevice:captureDevice error:&error];
    if (!input) {
        NSLog(@"%@",[error localizedDescription]);
        return;
    }
    //3.创建媒体数据输出流
    AVCaptureMetadataOutput * captureMetadataOutput = [[AVCaptureMetadataOutput alloc]init];
    //4.实例化捕捉会话
    self.captureSession = [[AVCaptureSession alloc]init];
    //4.1.将输入流添加到会话
    [self.captureSession addInput:input];
    //4.2.将输出流添加到会话中
    [self.captureSession addOutput:captureMetadataOutput];
    //5.1.设置代理,主线程里刷新
    [captureMetadataOutput setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    //5.2.设置输出媒体数据类型为 QRCode 与条形码兼容
    [captureMetadataOutput setMetadataObjectTypes:@[AVMetadataObjectTypeQRCode,AVMetadataObjectTypeCode128Code,AVMetadataObjectTypeEAN13Code,AVMetadataObjectTypeEAN8Code]];
    //6.实例化预览图层
    self.videoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc]initWithSession:_captureSession];
    //7.设置预览图层填充方式
    [self.videoPreviewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
    //8.设置图层的frame
    [self.videoPreviewLayer setFrame:_viewPreview.layer.bounds];
    //9.将图层添加到预览View的图层上
    [self.viewPreview.layer addSublayer:_videoPreviewLayer];
    //10.设置扫描范围
    captureMetadataOutput.rectOfInterest = CGRectMake(0.2f, 0.2f, 0.8f, 0.8f);
    //10.1.扫描框
    self.boxImageView = [[UIImageView alloc]initWithFrame:CGRectMake(self.viewPreview.bounds.size.width * 0.2f, self.viewPreview.bounds.size.height * 0.2f, self.viewPreview.bounds.size.width - self.viewPreview.bounds.size.width * 0.4f, self.viewPreview.bounds.size.height - self.viewPreview.bounds.size.height * 0.4f)];
    self.boxImageView.image = [UIImage imageNamed:@"456"];
    [self.viewPreview addSubview:_boxImageView];
    //10.2.扫描线
    self.scanView = [[UIImageView alloc]initWithFrame:CGRectMake(kP6width(15), 0, self.boxImageView.frame.size.width - kP6width(30), kP6Height(5))];
    self.scanView.image = [UIImage imageNamed:@"12345"];
    [self.boxImageView addSubview:_scanView];
    //11.定时器,让扫描线来回移动
    self.timer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(scanViewMove:) userInfo:nil repeats:YES];
    [_timer fire];
    //12.开始扫描
    [self.captureSession startRunning];
}

#pragma mark --- 停止扫描 <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
-(void)stopReading
{
    [self.captureSession stopRunning];
    self.captureSession = nil;
    [self.scanView removeFromSuperview];
    [self.videoPreviewLayer removeFromSuperlayer];
    [self.timer invalidate];
    self.timer = nil;
}

#pragma mark --- 实现定时器中的方法 <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
-(void)scanViewMove:(NSTimer *)timer
{
    CGRect frame = self.scanView.frame;
    if(!_upOrDown)
    {
        frame.origin.y += 1;
        self.scanView.frame = frame;
        if (self.scanView.frame.origin.y >= self.boxImageView.frame.size.height - kP6Height(10))
        {
            _upOrDown = YES;
        }
    }
    else
    {
        frame.origin.y -= 1;
        self.scanView.frame = frame;
        if(self.scanView.frame.origin.y <= 0)
        {
            _upOrDown = NO;
        }
    }
    
}

#pragma mark --- 实现代理方法 <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
-(void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
    //判断是否有数据
    if ([metadataObjects count] > 0) {
        AVMetadataMachineReadableCodeObject * metadataObj = [metadataObjects objectAtIndex:0];
        NSLog(@"%@--------",metadataObj.stringValue);
        
        [self stopReading];
        
        if (self.block)
        {
            self.block([metadataObj stringValue]);
        }
        
        [self jump];
    }
}
-(void)jump
{
    [self.navigationController popViewControllerAnimated:YES];
}

@end
